package com.web709.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.web709.common.CustomException;
import com.web709.common.R;
import com.web709.dto.DemandDto;
import com.web709.entity.*;
import com.web709.mapper.DemandMapper;
import com.web709.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class DemandServiceImpl extends ServiceImpl<DemandMapper, Demand> implements DemandService {
    @Autowired
    private DemandImgService demandImgService;
    @Autowired
    private VolunteerService volunteerService;

    @Autowired
    private PointsAccountsService pointsAccountsService;

    @Autowired
    private PointsTransactionsService pointsTransactionsService;

    private static final int MAX_IMAGES = 9;
    @Autowired
    private DemandService demandService;

    @Override
    public R<String> publishDemand(DemandDto demandDto) {
// 将 DemandDto 转换为 Demand 实体
        Demand demand = new Demand();
        BeanUtils.copyProperties(demandDto, demand);

// 保存 Demand 实体到数据库
        boolean saveResult = this.save(demand);

// 根据保存结果返回相应的响应
        if (saveResult) {
            return R.success("需求发布成功");
        } else {
            return R.error("需求发布失败");
        }
    }

    @Override
    public R<String> publishDemandWithImgs(DemandDto demandDto) {
        try {
            // 保存需求主体
            Demand demand = new Demand();
            BeanUtils.copyProperties(demandDto, demand);
            this.save(demand);

            // 保存图片记录
            if (demandDto.getImgList() != null && !demandDto.getImgList().isEmpty()) {
                List<DemandImg> imgEntities = demandDto.getImgList().stream()
                        .map(path -> new DemandImg(demand.getId(), path.trim()))
                        .collect(Collectors.toList());

                demandImgService.saveBatch(imgEntities);
            }

            return R.success("需求发布成功");
        } catch (Exception e) {
            log.error("需求发布失败：", e);
            throw new CustomException("需求发布失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> updateDemandWithImgs(DemandDto demandDto) {
        try {
            // 参数校验
            Validate.notNull(demandDto, "需求参数不能为空");
            Validate.notNull(demandDto.getId(), "需求ID不能为空");

            // 更新需求主体
            Demand demand = new Demand();
            BeanUtils.copyProperties(demandDto, demand);
            this.updateById(demand);

            // 处理图片更新（先删后插模式）
            processDemandImages(demand.getId(), demandDto.getImgList());

            return R.success("需求更新成功");
        } catch (IllegalArgumentException e) {
            log.warn("参数校验失败：{}");
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("需求更新失败[ID:{}]：{}");
            throw new CustomException("需求更新失败：" + e.getMessage());
        }
    }

    @Override
    public R<Page<DemandDto>> queryDemandsWithImgs(Page<DemandDto> page) {
        try {
            // 查询需求主体
            Page<Demand> demandPage = this.page(new Page<>(page.getCurrent(), page.getSize()),
                    new LambdaQueryWrapper<Demand>().orderByDesc(Demand::getCreateTime));

            // 获取所有需求ID
            List<Integer> demandIds = demandPage.getRecords().stream()
                    .map(Demand::getId)
                    .collect(Collectors.toList());

            // 查询需求图片
            List<DemandImg> demandImgList = demandImgService.list(new LambdaQueryWrapper<DemandImg>()
                    .in(DemandImg::getDemandId, demandIds));

            // 将图片按需求ID分组
            Map<Integer, List<DemandImg>> imgMap = demandImgList.stream()
                    .collect(Collectors.groupingBy(DemandImg::getDemandId));

            // 封装需求数据
            List<DemandDto> demandDtoList = demandPage.getRecords().stream()
                    .map(demand -> {
                        DemandDto demandDto = new DemandDto();
                        BeanUtils.copyProperties(demand, demandDto);

                        // 添加对应的图片列表
                        List<DemandImg> imgs = imgMap.getOrDefault(demand.getId(), Collections.emptyList());
                        demandDto.setImgList(imgs.stream().map(DemandImg::getImg).collect(Collectors.toList()));

                        return demandDto;
                    })
                    .collect(Collectors.toList());

            // 封装分页数据
            Page<DemandDto> demandDtoPage = new Page<>();
            BeanUtils.copyProperties(demandPage, demandDtoPage);
            demandDtoPage.setRecords(demandDtoList);

            return R.success(demandDtoPage);
        } catch (Exception e) {
            log.error("查询需求失败：", e);
            throw new CustomException("查询需求失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<String> deleteDemand(int demandId) {
        try {
            // 删除需求主体
            boolean deleteResult = this.removeById(demandId);

            // 删除需求图片
            LambdaQueryWrapper<DemandImg> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DemandImg::getDemandId, demandId);
            demandImgService.remove(wrapper);

            // 根据删除结果返回相应的响应
            if (deleteResult) {
                return ResponseEntity.ok("需求删除成功");
            } else {
                return ResponseEntity.ok("需求删除失败");
            }
        } catch (Exception e) {
            log.error("需求删除失败：", e);
            throw new CustomException("需求删除失败：" + e.getMessage());
        }
    }


    @Override
    @Transactional
    public ResponseEntity<String> receiveDemand(int demandId, int volunteerId) {
        //根据demandId查询demand信息
        Demand demand = this.getById(demandId);
        if (demand == null) {
            return ResponseEntity.ok("需求不存在");
        }
        if (demand.getStatus() != 0) {
            return ResponseEntity.ok("该需求已被接单");
        }
        //判断该用户是否已经接过该需求
        if ( demand.getVolunteerId() == volunteerId) {
            return ResponseEntity.ok("该用户已经接过该需求");
        }
        //根据volunteerId查询积分账户
        QueryWrapper<PointsAccounts> pointsAccountsQueryWrapper = new QueryWrapper<>();
        pointsAccountsQueryWrapper.eq("volunteer_id", volunteerId);
        PointsAccounts pointsAccounts = pointsAccountsService.getOne(pointsAccountsQueryWrapper);
        if (pointsAccounts == null) {
            PointsAccounts p = new PointsAccounts();
            p.setUserId(volunteerId);
            p.setTotalPoints(0);
            p.setRedeemedPoints(0);
            p.setRemainingPoints(0);
            pointsAccountsService.save(p);
        }
        //查询需求积分，更新积分到积分账户中
        Integer points = demand.getPoints();
        pointsAccountsService.update(new LambdaUpdateWrapper<PointsAccounts>()
                .eq(PointsAccounts::getUserId, volunteerId)
                .setSql("total_points = total_points + " + points)
                .setSql("remaining_points = remaining_points + " + points));

        //写入积分记录
        PointsTransactions pointsTransactions = new PointsTransactions();
        pointsTransactions.setUserId(volunteerId);
        pointsTransactions.setPointsChange(points);
        pointsTransactions.setReason("接单获得积分");
        pointsTransactions.setTransactionDate(LocalDateTime.now());
        pointsTransactionsService.save(pointsTransactions);
        this.update(new LambdaUpdateWrapper<Demand>()
                .eq(Demand::getId, demandId)
                .set(Demand::getStatus, 1)
                .set(Demand::getVolunteerId, volunteerId));
        return ResponseEntity.ok("接单成功");



    }



    /**
     * 处理需求图片（带事务传播）
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void processDemandImages(Integer demandId, List<String> imgList) {
        // 删除旧图片记录
        LambdaQueryWrapper<DemandImg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DemandImg::getDemandId, demandId);
        demandImgService.remove(wrapper);

        // 插入新记录（带有效性校验）
        if (CollectionUtils.isNotEmpty(imgList)) {
            // 校验图片数量
            if (imgList.size() > MAX_IMAGES) {
                throw new IllegalArgumentException("最多允许上传" + MAX_IMAGES + "张图片");
            }

            List<DemandImg> validImages = imgList.stream()
                    .filter(StringUtils::isNotBlank)  // 过滤空路径
                    .map(String::trim)                // 去除前后空格
                    .distinct()                       // 去重处理
                    .limit(MAX_IMAGES)                // 数量限制
                    .map(path -> new DemandImg(demandId, path))
                    .collect(Collectors.toList());

            if (!validImages.isEmpty()) {
                demandImgService.saveBatch(validImages);
            }
        }
    }



}
